<?php

namespace maotool\orm;

use maotool\core\facade\Config;
use maotool\log\Console;
use PDO;

class PdoTemplateUtil {

    private static $pdo = null;

    public static function getPdo()
    {
        if (isset(self::$pdo)) {
            return self::$pdo;
        } else {
            $config = Config::get("database.connections.mysql");
            Console::debug(["mysql:host=" . $config["hostname"] . ";port=" . $config["hostport"] . ";dbname=" . $config["database"] . ";charset=" . $config["charset"], $config["username"], $config["password"]]);
            $pdoParam = [
                PDO::ATTR_CASE => PDO::CASE_NATURAL,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
                PDO::ATTR_STRINGIFY_FETCHES => false,
                PDO::ATTR_EMULATE_PREPARES => false,
                PDO::ATTR_PERSISTENT => true,
            ];
            $pdo = new PDO("mysql:host=" . $config["hostname"] . ";port=" . $config["hostport"] . ";dbname=" . $config["database"] . ";charset=" . $config["charset"],
                $config["username"], $config["password"], $pdoParam);
            $pdo->query("SET NAMES {$config["charset"]}");
            return self::$pdo = $pdo;
        }
    }

    public static function update($sql, $ages = [])
    {
        $pdo = self::getPdo();
        $sth = $pdo->prepare($sql);
        for ($i = 0; $i < count($ages); $i++) {
            $sth->bindParam($i + 1, $ages[$i]);
        }
        $sth->execute();
        return $sth->rowCount();
    }

    public static function batchUpdate()
    {

    }

    public static function insert()
    {

    }

    public static function insertGetId()
    {

    }

    public static function query($sql, $ages = [])
    {
        $pdo = self::getPdo();
        $sth = $pdo->prepare($sql);
        for ($i = 0; $i < count($ages); $i++) {
            $sth->bindParam($i + 1, $ages[$i]);
        }
        $sth->execute();
        return $sth->fetch(PDO::FETCH_ASSOC);
    }

    public static function queryForObject($sql, $ages = [])
    {
        $pdo = self::getPdo();
        $sth = $pdo->prepare($sql);
        for ($i = 0; $i < count($ages); $i++) {
            $sth->bindParam($i + 1, $ages[$i]);
        }
        $sth->execute();
        return $sth->fetch(PDO::FETCH_OBJ);
    }

    public static function queryForList($sql, $ages = [])
    {
        $pdo = self::getPdo();
        $sth = $pdo->prepare($sql);
        for ($i = 0; $i < count($ages); $i++) {
            $sth->bindParam($i + 1, $ages[$i]);
        }
        $sth->execute();
        return $sth->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function execute($sql, $ages = [])
    {
        $pdo = self::getPdo();
        $sth = $pdo->prepare($sql);
        for ($i = 0; $i < count($ages); $i++) {
            $sth->bindParam($i + 1, $ages[$i]);
        }
        $sth->execute();
        return $sth->rowCount();
    }

}